import { Fragment } from 'react'
import { Navigate } from 'react-router-dom';
import { Form, Input, Button, Checkbox, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { userApi } from '../../api'

import { useRecoilState, useSetRecoilState } from 'recoil';
import { userState } from '../../store/'
import './login.less'

interface IProps {
  form?: any;
  isLoading?: boolean;
}

export default function Login (props: IProps) {
  const { login } = userApi;
  const [isLogin, setIsLogin] = useRecoilState(userState.loginAtom);
  const setUserInfo = useSetRecoilState(userState.userInfoAtom);

  const onFinish = (values: any) => {
    login(values).then((res: any) => {
      if (res.code === 200) {
        setIsLogin(true)
        setUserInfo(res.data)
      } else {
        setIsLogin(false)
        setUserInfo({})
      }
    }).catch((e) => {
      console.log(e)
      message.error('接口调用出错');
      // setIsLogin(true)
      // setUserInfo({})
    })
  };

  const onFinishFailed = (errorInfo: any) => {
    // console.log('Failed:', errorInfo);
    message.loading(errorInfo)
  };

  return (
    isLogin
    ?
    <Navigate to="/admin" />
    :
    <Fragment>
      <Card 
        title="登录管理后台" 
        className="login-wrapper"
      >
        <Form
          name="normal_login"
          className="login-form"
          // labelCol={{ span: 8 }}
          // wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: 'Please input your Username!' }]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: 'Please input your Password!' }]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <a className="login-form-forgot" href="">
              忘记密码
            </a>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </Fragment>
  )
}
